package com.keelau.jxbrowser;

import com.keelau.ui.swing.FxBrowerUI;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.ContextMenuHandler;
import com.teamdev.jxbrowser.chromium.ContextMenuParams;
import com.teamdev.jxbrowser.chromium.swing.internal.ContextMenuBuilder;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.CustomMenuItem;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FxBrowserContextMenu implements ContextMenuHandler {

    private final JComponent component;


    FxBrowerUI fxBrowerUI;

    public FxBrowserContextMenu(JComponent parentComponent,FxBrowerUI fxBrowerUI) {
        this.component = parentComponent;
        this.fxBrowerUI = fxBrowerUI;
    }

    public void showContextMenu(final ContextMenuParams params) {
        final JPopupMenu popupMenu = new JPopupMenu();
        if (!params.getLinkText().isEmpty()) {
            popupMenu.add(createMenuItem("在新窗口打开", new Runnable() {
                public void run() {
                    String linkURL = params.getLinkURL();
                    //System.out.println("linkURL = " + linkURL);
                    fxBrowerUI.createTabBrowser(null,linkURL);
                }
            }));
        }

        final Browser browser = params.getBrowser();
        popupMenu.add(createMenuItem("重新加载", new Runnable() {
            public void run() {
                browser.reload();
            }
        }));

        popupMenu.add(createMenuItem("复制源代码", new Runnable() {
            @Override
            public void run() {
                setSysClipboardText(browser.getHTML());
            }
        }));

        final Point location = params.getLocation();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                popupMenu.show(component, location.x+200, location.y+110);
            }
        });
    }

    public static void setSysClipboardText(String writeMe) {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection(writeMe);
        clip.setContents(tText, null);
    }

    private static JMenuItem createMenuItem(String title, final Runnable action) {
        JMenuItem reloadMenuItem = new JMenuItem(title);
        reloadMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                action.run();
            }
        });
        return reloadMenuItem;
    }
}
